package cn.iocoder.yudao.module.train.utils;


import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.train.controller.admin.order.vo.OrderSaveReqVO;
import cn.iocoder.yudao.module.train.controller.admin.payrefundorder.vo.PayRefundOrderRespVO;
import cn.iocoder.yudao.module.train.controller.admin.payrefundorder.vo.PayRefundOrderSaveReqVO;
import cn.iocoder.yudao.module.train.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.train.dal.dataobject.payrefundorder.PayRefundOrderDO;
import cn.iocoder.yudao.module.train.dal.dataobject.trade.TradeDO;
import cn.iocoder.yudao.module.train.service.payrefundorder.PayRefundOrderService;
import cn.iocoder.yudao.module.train.service.trade.TradeService;
import jakarta.annotation.Resource;

import java.math.BigDecimal;
import java.util.concurrent.ThreadLocalRandom;

public class OrderUtils {

    @Resource
    private static TradeService tradeService;

    @Resource
    private static PayRefundOrderService payRefundOrderService;

    public static String generateOrderSn(Long wxUserId) {
        return "YJ" + ThreadLocalRandom.current().nextInt(1000, 10000) + System.currentTimeMillis() + wxUserId;
    }

    public static String generateTradeSn(Long wxUserId) {
        return "TR" + ThreadLocalRandom.current().nextInt(1000, 10000) + System.currentTimeMillis() + wxUserId;
    }

    public static String generateRefundSn(Long wxUserId) {
        return "RF" + ThreadLocalRandom.current().nextInt(1000, 10000) + System.currentTimeMillis() + wxUserId;
    }
//
    public static TradeDO createTrade(Long wxUserId, BigDecimal payAmount) {
        TradeDO trTrade = new TradeDO();
        trTrade.setTradeSn(generateTradeSn(wxUserId));
        trTrade.setWxUserId(wxUserId);
        trTrade.setPayAmount(payAmount);
        trTrade.setStatus(0);
        trTrade.setCreator("wxUserId：" + wxUserId);
        return trTrade;
    }

    public static PayRefundOrderRespVO createRefundOrder(OrderSaveReqVO orderDto, String tradeSn) {
        PayRefundOrderDO trPayRefundOrder = new PayRefundOrderDO();
        trPayRefundOrder.setWxUserId(orderDto.getWxUserId());

        TradeDO trTrade = tradeService.getTradeByTradeSn(tradeSn);
        trPayRefundOrder.setTradeSn(trTrade.getTradeSn());
        trPayRefundOrder.setTradeNo(trTrade.getTradeNo());
        trPayRefundOrder.setRefundSn(generateRefundSn(orderDto.getWxUserId()));
        trPayRefundOrder.setPayAmount(trTrade.getPayAmount());
        trPayRefundOrder.setRefundAmount(orderDto.getRefundAmount());
        trPayRefundOrder.setCreator("wxUserId：" + orderDto.getWxUserId());
        payRefundOrderService.createPayRefundOrder(trPayRefundOrder);
        PayRefundOrderRespVO payRefundOrder = BeanUtils.toBean(trPayRefundOrder, PayRefundOrderRespVO.class);
        return payRefundOrder;
    }
}
